package cn.islu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",
        initParams = {@WebInitParam(name = "characterEncoding", value = "UTF8"),
                @WebInitParam(name = "contentType", value = "text/html;charset=UTF-8")})
public class EncodingFilter implements Filter {
    private String characterEncoding;
    private String contentType;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        characterEncoding = filterConfig.getInitParameter("characterEncoding");
        contentType = filterConfig.getInitParameter("contentType");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding(characterEncoding);
        response.setContentType(contentType);

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
